function assert(exp,msg){
	if(!exp){
		throw new Error(msg || '不能为空')
	}
}
const Reg={
	int:/^-?[1-9][0-9]?.?[0-9]*$/,
	mobile:/^1[3456789]\d{9}$/,
	phone:/\d{3}-\d{8}|\d{4}-\d{7}/,
	email:/^\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*$/,
	password:/^.{6,16}/,
	inviteCode:/^[a-zA-Z0-9]{1,}$/
}
const commonStrategiesFn = (reg)=>{
	return (val,msg)=>{
		if(!reg.test(val)){
			return msg
		}
	}
}
let strategies ={
	notEmpty:(val,msg)=>{
		if(!val){
			return msg
		}
	},
	// 手机号
	mobile:commonStrategiesFn(Reg.mobile),
	// 固定电话
	phone:commonStrategiesFn(Reg.phone),
	// 邮箱
	email:commonStrategiesFn(Reg.email),
	// 判断验证码格式
	inviteCode:commonStrategiesFn(Reg.inviteCode),
	// 判断字符长度范围
	lengthRange:({val,min,max},msg)=>{
		val = String(val);
		if(min && val.length<min){
			return msg
		}
		if(max && val.length>max){
			return msg
		}
	},
	equals:({val1,val2},msg)=>{
		if(val1!==val2){
			return msg
		}
	}
}
class Validate{
	constructor(data,rules) {
		assert(data)
		assert(rules)
		this.cache = []
		this.data = data
		this.rules = rules
	}
	__addValidateFn(){
		let rules = this.rules
		let data = this.data
		for(let rule of rules){
			let {name,type,required,min,max,eqName,emptyMsg,errMsg} = rule
			
			if(!errMsg){
				errMsg=`请输入正确的${name}`
			}
			if(!emptyMsg){
				emptyMsg = `${name}不能为空`
			}
			if(required){
				this.cache.push(function(){
					return strategies['notEmpty'](data[name],emptyMsg)
				})
			}
			// 有值，校验
			data[name] && this.__typeValidate({name,type,required,min,max,eqName,emptyMsg,errMsg})
			
		}
	}
	__typeValidate({name,type,required,min,max,eqName,emptyMsg,errMsg}){
		let data = this.data
		if(type=='lengthRange'){
			this.cache.push(function(){
				return strategies[type] && strategies[type]({val:data[name],min,max},errMsg)
			})
		}else if(type=='equals'){
			this.cache.push(function(){
				return strategies[type] && strategies[type]({val1:data[name],val2:data[eqName]},errMsg)
			})
		}else{
			this.cache.push(function(){
				return strategies[type] && strategies[type](data[name],errMsg)
			})
		}
	}
	check(){
		this.__addValidateFn()
		let result = {isOk:true,msg:''};
		for(let i=0;i<this.cache.length;i++){
			let msg = this.cache[i]()
			let isOk = true
			if(msg){
				result = {isOk:false,msg}
				break;
			}
		}
		return result
	}
	addRule(ruleName,ruleFn){
		strategies[ruleName] = ruleFn
	}
}

 
